// pages/index/index.js
const app = getApp()
import {
  getDays
} from '../../utils/dateTime.js'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    user_img: '/img/userImg.png',
    userId: '',
    user: {
      userName: '用户名',
    },
    inviteList: [],
    totalPeople: 0,
    totalMoney: 0.0,
    todayPeople: 0,
    todayMoney: 0.0,
    secPeople: 0,
    getDays,
    addShow: false,
    inviteMoney: 0,
    tiShow: false,
    tiIndex: -1,
    tiMoney: 0,
    userType: -1,
    tipShow: false, //代理商公告
    isFinishUser: false,
    cashNum: 0,
    adduserInfo: {
      name: "",
      tel: ''
    }
  },

  getList() {
    ks.showLoading({
      title: '',
      icon: 'none',
    })
    var that = this;
    var url = app.globalData.url + "nine/getGeren";
    app.wxRequest(url, {
      userId: that.data.userId,
    }, res => {
      console.log(res);
      if (res.flag) {

        app.globalData.userInfo = res.data.nineUser

        var list = res.data.inviteList;
        var totalPeople = 0;
        var totalMoney = 0.0;
        var todayPeople = 0;
        var todayMoney = 0.0;
        var secPeople = 0;
        for (var i in list) {
          var num = getDays(res.data.currentTime.split(' ')[0], list[i].dateTime.split(' ')[0]);
          if (list[i].parentId == 0) { //直接邀请的用户
            totalMoney += list[i].getMoney;
            totalPeople++;
            if (num == 0) {
              todayMoney += 10;
              todayPeople++;
            }
          } else {
            if (num == 0) {
              secPeople++;
              // todayMoney += 2.9;
            }
          }

        }
        var name = res.data.nineUser.userName == null ? '用户名' : res.data.nineUser.userName
        res.data.nineUser.userName = res.data.nineUser.userName == null ? '用户名' : res.data.nineUser.userName
        if (res.data.nineUser.payStatus == 1) {
          res.data.nineUser.invalidTime = res.data.nineUser.invalidTime.split('.')[0]
        }
        var user = that.data.user
        user.name = name
        var cashList = res.data.cashList;
        var cashNum = 0;
        for (var i in cashList) {
          cashNum += cashList[i].cashNumber;
        }
        ks.hideLoading();


        totalMoney = totalMoney - cashNum;
        that.setData({
          user: res.data.nineUser,
          totalPeople: totalPeople,
          totalMoney: totalMoney,
          todayPeople: todayPeople,
          todayMoney: todayMoney,
          userName: name,
          secPeople: secPeople,
          isFinishUser: res.data.nineUser.userName != null
        })
        console.log(that.data.isFinishUser);
      }
      wx.stopPullDownRefresh()
    })
  },
  inputHandle(e) {
    var str = e.currentTarget.dataset.flag
    var val = e.detail.value
    this.setData({
      [str]: val
    })
    console.log(e);
  },
  // 提交信息
  formSubmit(e) {
    console.log(e);
    var name = e.detail.value.nickname,
      tel = e.detail.value.tel
    console.log(name);
    console.log(tel);

    if (name == '') {
      wx.showToast({
        title: '请填写昵称',
        icon: 'none'
      })
      return
    } else if (!this.validator(tel)) {
      wx.showToast({
        title: '手机号输入有误',
        icon: 'none'
      })
      return
    }

    var that = this;
    var url = app.globalData.url + "nine/updateUsers";
    app.wxRequest(url, {
      userId: that.data.userId,
      str: name,
      tel: tel
    }, res => {
      console.log(res);
      if (res.flag) {
        wx.showToast({
          title: '修改成功',
          icon: 'none'
        })
        var userInfo = app.globalData.userInfo;
        console.log(userInfo);
        userInfo.userName = name;
        userInfo.userTel = tel;
        app.globalData.userInfo = userInfo;
        wx.setStorageSync('userInfo', JSON.stringify(userInfo));
        that.setData({
          userName: e.detail.value.nickname,
          userTel: e.detail.value.tel,
          addShow: false
        })
        this.getList()
      }
    })
  },
  infotapBasicMask() {
    console.log(122);
    this.setData({
      addShow: false
    })
  },


  toPage(e) {
    var flag = e.currentTarget.dataset.flag
    if (flag == 'his') {
      wx.navigateTo({
        url: '/packageA/pages/testHistory/testHistory',
      })
    } else if (flag == 'amount') {
      var str = JSON.stringify(this.data.user)
      wx.navigateTo({
        url: '/packageB/pages/nineAmount/nineAmount?obj=' + str,
      })
    }
  },

  showhandle() {
    this.setData({
      addShow: true
    })
  },
  onClose() {
    this.setData({
      tipShow: false
    })
  },


  choseAHandle(e) {
    console.log(e);
    var str = e.detail.avatarUrl
    this.setData({
      user_img: str
    })
  },
  tiHandle() {
    console.log(this.data.isFinishUser);
    if (!this.data.isFinishUser) {
      wx.showToast({
        title: '请先完善用户基本信息',
        icon: 'none'
      })
      return
    }
    this.setData({
      tiShow: true
    })
  },
  selectMoney(e) {
    var num = e.currentTarget.dataset.num
    console.log(num);
    if (num > this.data.totalMoney) {
      return wx.showToast({
        title: '账户余额不足',
        icon: 'none'
      })
    }
    this.setData({
      tiMoney: num
    })
  },
  onTiClose() {
    this.setData({
      tiShow: false,
      tiMoney: 0
    })
  },

  onTipClose() {
    this.setData({
      tipShow: false,
    })
  },
  tipShowHandle() {
    this.setData({
      tipShow: true
    })
  },

  callHandle() {

    wx.makePhoneCall({
      phoneNumber: '0431-8188-3496',
    })

  },





  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
    console.log(app.globalData.userId);
    this.setData({
      userId: app.globalData.userId,
      userType: app.globalData.userType,
    })
    console.log(this.data.userType);
    this.getList();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {


  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        // 当前页面的 tabBar 索引
        selected: 2
      })
    }
    this.setData({
      userId: app.globalData.userId,
      userType: app.globalData.userType,
    })
    console.log(this.data.userType);

  },
  onShareAppMessage() {
    var agentId = 0;
    agentId = this.data.userType == 1 ? this.data.user.userId : this.data.user.agentId
    let myObj = {
      title: '九型人格',
      path: "/pages/index/index?scene=" + app.globalData.userId + '&agentId=' + agentId,
      imageUrl: '/img/shareImg.png'
    }
    return myObj;
  },
  onShareTimeline() {
    var agentId = 0;
    agentId = this.data.userType == 1 ? this.data.user.userId : this.data.user.agentId
    let myObj = {
      title: '九型人格',
      path: "/pages/index/index?scene=" + app.globalData.userId + '&agentId=' + agentId,
      imageUrl: '/img/shareImg.png'
    }
    return myObj;
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.getList();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() { },

  // 验证手机号 和座机号
  validator: function (val) {
    return /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[189]))\d{8}$/.test(val) || /^(?:(?:\d{3}-)?\d{8}|^(?:\d{4}-)?\d{7,8})(?:-\d+)?$/.test(val);
  },
  toCash() {
    var that = this;
    console.log(that.data.tiMoney);
    if (that.data.tiMoney == 0) {
      return wx.showToast({
        title: '请选择金额',
        icon: 'none'
      })
    }
    var url = app.globalData.url + 'nine/toGetMoney';
    console.log(that.data.user.userName);

    var realTiMoney = (that.data.tiMoney * 0.92).toFixed(2)
    console.log(realTiMoney);

    app.wxRequest(url, {
      userId: app.globalData.userId,
      openId: app.globalData.openId,
      userName: that.data.user.userName,
      totalMoney: realTiMoney,
    }, res => {
      console.log(res);
      var result = JSON.parse(res.data.datas);
      if (!result.batch_id) {
        wx.showToast({
          title: '失败,' + result.message,
        })
        that.setData({
          tiShow: false
        })
      } else {
        wx.showToast({
          title: '提现成功',
        })
        that.setData({
          totalMoney: that.data.totalMoney - that.data.tiMoney,
        })
        app.wxRequest(app.globalData.url + 'nine/addCashRecords', {
          userId: app.globalData.userId,
          totalMoney: that.data.tiMoney,
          orderNum: result.out_batch_no,
        }, ress => {
          console.log(ress);
          // if(res.data.){}


        }, errr => { })
      }


    }, err => { })
  },


})